<template>
	<view class="login-container">
		<!-- 登录表单 -->
		<u-form :model="loginForm" errorType="message" :rules="rules" ref="loginFormRef" class="login-form">
			<!-- 姓名 -->
			<u-form-item label="姓名" :required="true" labelWidth="65" prop="name">
				<u--input v-model="loginForm.name" placeholder="请输入您的姓名"></u--input>
			</u-form-item>
			<!-- 手机号 -->
			<u-form-item label="手机号" :required="true" labelWidth="65" prop="phone">
				<u--input v-model="loginForm.phone" placeholder="请输入您的手机号"></u--input>
			</u-form-item>
			<!-- 验证码 -->
			<u-form-item label="验证码" labelWidth="65" prop="code">
				<u--input v-model="loginForm.code" placeholder="请填写验证码">
					<template slot="suffix">
						<u-button :disabled="!canSendCode" type="success" size="mini" @click="handleSendCode">
							{{ codeButtonText }}
						</u-button>
					</template>
				</u--input>
			</u-form-item>
			<!-- 登录按钮 -->
			<view class="login-button">
				<u-button type="primary" @click="handleLogin">登录</u-button>
			</view>
		</u-form>
	</view>
</template>
<script>
import { auth } from "@/api";
import { ERROR_TYPE, LOGIN_FORM_RULES } from "@/common/constants";
import { hideLoading, showLoading, showMessage } from "@/common/utils";
import { ROUTE_PATHS } from "@/router/routes";

export default {
	name: "LoginPage",
	data() {
		return {
			/**
			 * 是否可以发送验证码
			 * @type {boolean}
			 */
			canSendCode: true,
			/**
			 * 短信重发倒计时
			 * @type {number}
			 */
			countdown: 0,
			/**
			 * 登录表单
			 * @type {object}
			 * @property {string} name 姓名
			 * @property {string} phone 手机号
			 * @property {string} code 验证码
			 */
			loginForm: {
				name: "",
				phone: "",
				code: ""
			},
			rules: LOGIN_FORM_RULES,
			redirect: "",
		};
	},
	computed: {
		codeButtonText() {
			return this.canSendCode ? "获取验证码" : `${this.countdown}后重新发送`;
		}
	},
	onLoad(options) {
		this.redirect = options.redirect || ROUTE_PATHS.HOME;
	},
	methods: {
		/**
		 * 验证表单字段
		 * @param field 字段名
		 */
		async validateField(field) {
			try {
				await new Promise((resolve, reject) => {
					this.$refs.loginFormRef.validateField(field, (errList) => {
						errList.length ? reject(errList[0]) : resolve(true);
					});
				});
				return true;
			} catch (error) {
				return false;
			}
		},
		/**
		 * 短信重发倒计时
		 */
		startCountdown() {
			this.canSendCode = false;
			this.countdown = 30;
			
			const timer = setInterval(() => {
				if (this.countdown <= 1) {
					clearInterval(timer);
					this.canSendCode = true;
				}
				this.countdown--;
			}, 1000);
		},
		/**
		 * 发送验证码
		 */
		async handleSendCode() {
			try {
				if (await this.validateField("phone")) {
					showLoading("验证码发送中...");
					const { data } = await auth.getSmsCode({
						phone: this.loginForm.phone
					});
					this.loginForm.code = data.code;
					showMessage("验证码已发送");
					this.startCountdown();
				}
			} catch (error) {
				if (error.type === ERROR_TYPE.NETWORK) {
					return;
				}
				showMessage(error.msg || "验证码发送失败", false);
			} finally {
				hideLoading();
			}
		},

		/**
		 * 登录
		 */
		async handleLogin() {
			try {
				showLoading("登录中...");
				await this.$refs.loginFormRef.validate();
				await this.$store.dispatch("user/login", {
					name: this.loginForm.name,
					phone: this.loginForm.phone,
					code: this.loginForm.code
				});
				this.$Router.push({ path: this.redirect });
			} catch (error) {
				if (error.type === ERROR_TYPE.NETWORK) {
					return;
				}
				showMessage(error.msg || "登录失败，请检查输入是否有误", false);
			} finally {
				hideLoading();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.login-container {
	
	.login-form {
		display: flex;
		flex-direction: column;
		margin-top: var(--margin-large);
		padding: 0 var(--margin-medium);

		.login-button {
			margin-top: var(--margin-base);
			width: 100%;
		}
	}
}
</style>
